﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Browser;

namespace Songhay.Silverlight.ApplicationLoader
{
    using Views;

    /// <summary>
    /// The Application Pre-Loader Application
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        public App()
        {
            this.Startup += (s, args) =>
            {
                this.RootVisual = new UserControlOne(this.Host);
            };

            this.UnhandledException += (s, args) =>
            {
                if(Debugger.IsAttached) return;
                args.Handled = true;
                Deployment
                    .Current
                    .Dispatcher
                    .BeginInvoke(new Action<ApplicationUnhandledExceptionEventArgs>((e) =>
                {
                    try
                    {
                        string errorMsg = e.ExceptionObject.Message +
                            e.ExceptionObject.StackTrace;

                        errorMsg = errorMsg
                            .Replace('"', '\'')
                            .Replace("\r\n", @"\n");

                        HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
                    }
                    catch(Exception)
                    {
                    }
                }));
            };

            InitializeComponent();
        }
    }
}
